<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { MarketItemApi } from '@/api/new/MarketItemApi.ts';
import { SecondHandItemApi } from '@/api/SecondHandItemApi.js';
import UserUtil from '@/utils/User/User.js';
import { ChatSessionApi } from '@/api/ChatSessionApi.js';
import apiClient from '@/api/axios.js';
import { AddressApi } from '@/api/new/userAddrApi.ts';
import MapUtils from '@/utils/Map/MapUtils';
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import { ArrowLeft, Clock, CircleCheck, CircleClose } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const orderID = ref(Number(route.params.id));
const orderInfo = ref({});
const productInfo = ref({});
const productImage = ref('');
const sellerInfo = ref({});
const addressInfo = ref({});
const loading = ref(true);
const submitting = ref(false);
const transactionLocation = ref('正在加载交易地点...');

// 默认图片
const defaultImage = 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png';
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 获取订单信息
const fetchOrderInfo = async () => {
  loading.value = true;
  try {
    console.log('获取订单详情:', orderID.value);
    
    // 获取订单详情
    const response = await apiClient.get(`/transactionorder/${orderID.value}`);
    console.log('订单详情响应:', response);
    
    if (response && response.data) {
      orderInfo.value = response.data;
    } else {
      orderInfo.value = {};
      ElMessage.warning('未找到订单信息');
      return;
    }
    
    console.log('处理后的订单信息:', orderInfo.value);
    
    // 获取商品信息
    if (orderInfo.value.itemID) {
      try {
        const productResponse = await SecondHandItemApi.getSecondHandItemById(orderInfo.value.itemID);
        console.log('商品详情响应:', productResponse);
        
        if (productResponse && productResponse.data) {
          productInfo.value = productResponse.data;
        } else if (productResponse) {
          productInfo.value = productResponse;
        } else {
          productInfo.value = {};
        }
        
        console.log('处理后的商品信息:', productInfo.value);
      } catch (error) {
        console.error('获取商品信息失败:', error);
        productInfo.value = {};
      }
      
      // 获取商品图片
      try {
        const imageResponse = await MarketItemApi.getFirstItemImage(orderInfo.value.itemID);
        console.log('商品图片响应:', imageResponse);
        
        if (imageResponse) {
          if (typeof imageResponse === 'string') {
            try {
              const parsedImage = JSON.parse(imageResponse);
              productImage.value = parsedImage.imageUrl || defaultImage;
            } catch (e) {
              productImage.value = imageResponse || defaultImage;
            }
          } else if (imageResponse.imageUrl) {
            productImage.value = imageResponse.imageUrl;
          } else {
            productImage.value = defaultImage;
          }
        } else {
          productImage.value = defaultImage;
        }
        
        console.log('处理后的商品图片:', productImage.value);
      } catch (error) {
        console.error('获取商品图片失败:', error);
        productImage.value = defaultImage;
      }
    }
    
    // 获取卖家信息 - 修改为使用 UserProfileApi
    if (orderInfo.value.sellerID) {
      try {
        // 使用 UserProfileApi 替代 UserUtil.getUserInfoById
        const sellerResponse = await UserProfileApi.getUserInfo(orderInfo.value.sellerID);
        console.log('卖家信息响应:', sellerResponse);
        
        // 处理响应数据
        if (sellerResponse) {
          if (typeof sellerResponse === 'string') {
            try {
              sellerInfo.value = JSON.parse(sellerResponse);
            } catch (e) {
              sellerInfo.value = { username: '未知用户', headshot: defaultAvatar };
            }
          } else {
            sellerInfo.value = sellerResponse;
          }
        } else {
          sellerInfo.value = { username: '未知用户', headshot: defaultAvatar };
        }
        
        console.log('处理后的卖家信息:', sellerInfo.value);
      } catch (error) {
        console.error('获取卖家信息失败:', error);
        sellerInfo.value = { username: '未知用户', headshot: defaultAvatar };
      }
    }
    
    // 获取地址信息
    if (orderInfo.value.addrID) {
      try {
        const addressResponse = await AddressApi.getAddressById(orderInfo.value.addrID);
        console.log('地址信息响应:', addressResponse);
        addressInfo.value = addressResponse || {};
      } catch (error) {
        console.error('获取地址信息失败:', error);
        addressInfo.value = {};
      }
    }
  } catch (error) {
    console.error('获取订单信息失败:', error);
    ElMessage.error(`获取订单信息失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

// 获取交易地点信息
const fetchTransactionLocation = async () => {
  if (orderInfo.value && orderInfo.value.longitude && orderInfo.value.latitude) {
    try {
      transactionLocation.value = await MapUtils.getSimpleAddress(
        orderInfo.value.longitude,
        orderInfo.value.latitude
      );
    } catch (error) {
      console.error('获取交易地点信息失败:', error);
      transactionLocation.value = '未知交易地点';
    }
  } else {
    transactionLocation.value = '未设置交易地点';
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    'inProgress': '交易中',
    'completed': '已完成',
    'cancelled': '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 联系卖家
const contactSeller = async () => {
  const userInfo = await UserUtil.getUserInfo();
  if (!userInfo || !userInfo.userID) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    // 创建聊天会话
    const response = await MarketItemApi.createChatSession(userInfo.userID, orderInfo.value.sellerID, orderInfo.value.itemID);
    const res = typeof response === 'string' ? JSON.parse(response) : response;
    
    if (res.status === 'error') {
      console.log('触发了聊天创建的error');
      console.log('尝试通过用户id获取聊天id');
      
      // 使用 ChatSessionApi 获取已存在的聊天会话
      try {
        const chatSession = await ChatSessionApi.getChatSessionByUserIds(userInfo.userID, orderInfo.value.sellerID);
        if (chatSession && chatSession.chatSessionID) {
          // 跳转到聊天页面
          router.push(`/chat?chatSessionID=${chatSession.chatSessionID}&otherUserID=${orderInfo.value.sellerID}`);
        } else {
          ElMessage.error('无法获取聊天会话');
        }
      } catch (error) {
        ElMessage.error(`获取聊天会话失败: ${error.message}`);
      }
    } else if (res.status === 'success' && res.chatSession) {
      console.log('聊天创建成功', res);
      // 跳转到聊天页面
      router.push(`/chat?chatSessionID=${res.chatSession.chatSessionID}&otherUserID=${orderInfo.value.sellerID}`);
    } else {
      ElMessage.error('创建聊天会话失败：返回数据格式不正确');
    }
  } catch (error) {
    ElMessage.error(`创建聊天失败: ${error.message}`);
  }
};

// 确认收货
const confirmReceipt = async () => {
  try {
    await ElMessageBox.confirm('确认已收到商品并完成交易？', '确认收货', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    submitting.value = true;
    
    // 更新订单状态为已完成
    await MarketItemApi.updateOrderStatus(orderID.value, 'completed');
    
    // 更新商品状态为已售出
    await SecondHandItemApi.updateSecondHandItem(orderInfo.value.itemID, {
      ...productInfo.value,
      status: 'sold'
    });
    
    ElMessage.success('交易已完成');
    
    // 刷新订单信息
    fetchOrderInfo();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`确认收货失败: ${error.message}`);
    }
  } finally {
    submitting.value = false;
  }
};

// 取消订单
const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm('确认取消订单？取消后无法恢复', '取消订单', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    submitting.value = true;
    
    // 更新订单状态为已取消
    await MarketItemApi.updateOrderStatus(orderID.value, 'cancelled');
    
    // 更新商品状态为待售
    await SecondHandItemApi.updateSecondHandItem(orderInfo.value.itemID, {
      ...productInfo.value,
      status: 'forSale'
    });
    
    ElMessage.success('订单已取消');
    
    // 刷新订单信息
    fetchOrderInfo();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`取消订单失败: ${error.message}`);
    }
  } finally {
    submitting.value = false;
  }
};

// 评价订单
const rateOrder = () => {
  router.push(`/secondhand/rate/${orderID.value}`);
};

// 返回订单列表
const goBack = () => {
  router.push('/user/order');
};

onMounted(() => {
  fetchOrderInfo();
  fetchTransactionLocation();
});
</script>

<template>
  <div class="order-detail-container">
    <div class="page-header">
      <div class="back-button" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
        返回订单列表
      </div>
      <div class="page-title">订单详情</div>
    </div>
    
    <div v-if="loading" class="loading">
      <el-skeleton :rows="10" animated />
    </div>
    
    <template v-else>
      <!-- 订单状态 -->
      <div class="order-status-section">
        <div class="status-icon" :class="orderInfo.status">
          <el-icon v-if="orderInfo.status === 'inProgress'"><Clock /></el-icon>
          <el-icon v-else-if="orderInfo.status === 'completed'"><CircleCheck /></el-icon>
          <el-icon v-else-if="orderInfo.status === 'cancelled'"><CircleClose /></el-icon>
        </div>
        <div class="status-text">{{ getStatusText(orderInfo.status) }}</div>
      </div>
      
      <!-- 收货地址 -->
      <div class="info-section">
        <div class="section-title">收货信息</div>
        <div class="address-info">
          <div class="address-detail">{{ addressInfo.address }}</div>
          <div class="contact-info">{{ addressInfo.phone }}</div>
        </div>
      </div>
      
      <!-- 商品信息 -->
      <div class="info-section">
        <div class="section-title">商品信息</div>
        <div class="product-card">
          <div class="product-image" :style="{ backgroundImage: `url(${productImage || defaultImage})` }"></div>
          <div class="product-info">
            <div class="product-title">{{ productInfo.title }}</div>
            <div class="product-price">¥{{ productInfo.price }}</div>
          </div>
        </div>
      </div>
      
      <!-- 卖家信息 -->
      <div class="info-section">
        <div class="section-title">卖家信息</div>
        <div class="seller-info">
          <div class="seller-avatar">
            <img :src="sellerInfo.headshot || defaultAvatar" alt="卖家头像" />
          </div>
          <div class="seller-detail">
            <div class="seller-name">{{ sellerInfo.username || '未知用户' }}</div>
            <el-button type="primary" size="small" @click="contactSeller">联系卖家</el-button>
          </div>
        </div>
      </div>
      
      <!-- 订单信息 -->
      <div class="info-section">
        <div class="section-title">订单信息</div>
        <div class="order-info-list">
          <div class="info-item">
            <span class="label">订单编号</span>
            <span class="value">{{ orderID }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间</span>
            <span class="value">{{ formatDate(orderInfo.createTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">订单状态</span>
            <span class="value">{{ getStatusText(orderInfo.status) }}</span>
          </div>
          <div class="info-item">
            <span class="label">商品金额</span>
            <span class="value price">¥{{ productInfo.price || '0.00' }}</span>
          </div>
          <div class="info-item">
            <span class="label">运费</span>
            <span class="value">¥0.00</span>
          </div>
          <div class="info-item total">
            <span class="label">实付款</span>
            <span class="value price">¥{{ productInfo.price || '0.00' }}</span>
          </div>
          <div class="info-item">
            <span class="label">交易地点</span>
            <span class="value">{{ transactionLocation }}</span>
          </div>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <template v-if="orderInfo.status === 'inProgress'">
          <el-button type="primary" @click="confirmReceipt" :loading="submitting">确认收货</el-button>
          <el-button @click="contactSeller">联系卖家</el-button>
          <el-button type="danger" @click="cancelOrder" :loading="submitting">取消订单</el-button>
        </template>
        <template v-else-if="orderInfo.status === 'completed'">
          <el-button type="primary" @click="rateOrder" v-if="!orderInfo.hasRated">评价订单</el-button>
          <el-button @click="contactSeller">联系卖家</el-button>
        </template>
        <template v-else-if="orderInfo.status === 'cancelled'">
          <el-button @click="goBack">返回订单列表</el-button>
        </template>
      </div>
    </template>
  </div>
</template>

<style scoped lang="less">
.order-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
  
  .page-header {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    
    .back-button {
      display: flex;
      align-items: center;
      cursor: pointer;
      color: #666;
      font-size: 14px;
      
      &:hover {
        color: #ff2442;
      }
      
      .el-icon {
        margin-right: 4px;
      }
    }
    
    .page-title {
      margin-left: auto;
      font-size: 20px;
      font-weight: 600;
      color: #333;
    }
  }
  
  .loading {
    padding: 24px;
    background-color: #fff;
    border-radius: 8px;
  }
  
  .order-status-section {
    display: flex;
    align-items: center;
    padding: 24px;
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 16px;
    
    .status-icon {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      &.inProgress {
        background-color: #e6f7ff;
        color: #1890ff;
      }
      
      &.completed {
        background-color: #f6ffed;
        color: #52c41a;
      }
      
      &.cancelled {
        background-color: #fff2f0;
        color: #ff4d4f;
      }
      
      .el-icon {
        font-size: 24px;
      }
    }
    
    .status-text {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }
  
  .info-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 16px;
    
    .section-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 16px;
      padding-bottom: 12px;
      border-bottom: 1px solid #eee;
    }
    
    .address-info {
      .address-detail {
        font-size: 16px;
        margin-bottom: 8px;
      }
      
      .contact-info {
        font-size: 14px;
        color: #666;
      }
    }
    
    .product-card {
      display: flex;
      align-items: center;
      
      .product-image {
        width: 80px;
        height: 80px;
        background-size: cover;
        background-position: center;
        border-radius: 8px;
        margin-right: 16px;
      }
      
      .product-info {
        flex: 1;
        
        .product-title {
          font-size: 16px;
          margin-bottom: 8px;
        }
        
        .product-price {
          font-size: 16px;
          color: #ff2442;
          font-weight: 600;
        }
      }
    }
    
    .seller-info {
      display: flex;
      align-items: center;
      
      .seller-avatar {
        margin-right: 16px;
        
        img {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          object-fit: cover;
        }
      }
      
      .seller-detail {
        .seller-name {
          font-size: 16px;
          margin-bottom: 8px;
        }
      }
    }
    
    .order-info-list {
      .info-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;
        
        &.total {
          margin-top: 16px;
          padding-top: 16px;
          border-top: 1px solid #eee;
          font-weight: 500;
        }
        
        .label {
          color: #666;
        }
        
        .value {
          color: #333;
          
          &.price {
            color: #ff2442;
            font-weight: 600;
          }
        }
      }
    }
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin-top: 24px;
    
    @media (max-width: 576px) {
      flex-direction: column;
      
      .el-button {
        width: 100%;
      }
    }
  }
}
</style>